package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.YddArticle;
import com.itheima.ydd.entity.YddCate;
import com.itheima.ydd.mapper.YddCateMapper;
import com.itheima.ydd.service.IYddArticleService;
import com.itheima.ydd.service.IYddCateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.vo.YddCateVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class YddCateServiceImpl extends ServiceImpl<YddCateMapper, YddCate> implements IYddCateService {
    /**
     * 分页条件查询
     * @param catename
     * @param page
     * @param limit
     * @return
     */
    @Autowired
    private IYddArticleService yddArticleService;

    @Override
    public ResultData getYddcatePage(String catename, Integer page, Integer limit) {

        //修改变量名称
        Integer pageSize=limit;

        //分页查询
        Page<YddCate> pageInfo =new Page<>(page,pageSize); //page 起始页面 ?  pageSize= 页面条数?

        //条件查询
        LambdaQueryWrapper<YddCate> yddCateWrapper =new LambdaQueryWrapper<>();
        //模糊查询，确定catename存在不为空则条件成立
        yddCateWrapper.like(StringUtils.isNotEmpty(catename),YddCate::getCatename,catename);
        //进行条件分页查询
        pageInfo = page(pageInfo, yddCateWrapper);

        //包装返回值
        YddCateVo yddCateVo = new YddCateVo();
        yddCateVo.setData(pageInfo.getRecords());
        yddCateVo.setTotalPages(pageInfo.getTotal());
        yddCateVo.setCount(pageInfo.getTotal());
        yddCateVo.setPageSize(pageInfo.getSize());
        yddCateVo.setCurrentPage(pageInfo.getCurrent());
        return ResultData.ok("", yddCateVo);
    }

    @Override
    public void remove(Integer id) {
        LambdaQueryWrapper<YddArticle> advimgWrapper=new LambdaQueryWrapper<>();
        //添加查询条件，根据分类id进行查询
        advimgWrapper.eq(YddArticle::getCateid,id);
        int count = yddArticleService.count(advimgWrapper);
        //查询当前分类是否关联，如果关联，抛出一个业务异常
        if (count > 0) {
            //throw new Exception();
            throw new BusinessException("系统默认数据，不允许删除");
        }
        //正常删除分类
        super.removeById(id);
    }
}
